<!--
 * @Description: 全部商品页面组件(包括全部商品,商品分类,商品搜索)
 * @Author: hai-27
 * @Date: 2020-02-07 16:23:00
 * @LastEditors: hai-27
 * @LastEditTime: 2020-03-08 12:11:13
 -->
<template>
  <div class="goods" id="goods" name="goods">
    <!-- 面包屑 -->
    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item to="/">首页</el-breadcrumb-item>
        <el-breadcrumb-item>全部商品</el-breadcrumb-item>
        <el-breadcrumb-item v-if="search">搜索</el-breadcrumb-item>
        <el-breadcrumb-item v-else>分类</el-breadcrumb-item>
        <el-breadcrumb-item v-if="search">{{search}}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- 面包屑END -->

    <!-- 分类标签 -->
    <div class="nav">
      <div class="product-nav">
        <div class="title">分类</div>
        <div class="category-tabs">
          <div
              v-for="item in categoryList"
              :key="item.category_id"
              class="category-item"
              :class="{ 'active': activeName === ''+item.category_id }"
              @click="selectOrExpand(item)"
          >
<!--            如果 id为0 则显示全部分类 -->
            <span class="category-name">{{ item.category_id == 0 ? "全部商品" : item.name }}</span>
            <i
                v-if="hasSubCategories(item.id) || expandedCategories[item.id]"
                class="el-icon-arrow-down expand-icon"
                :class="{ 'expanded': expandedCategories[item.id] }"
            ></i>
          </div>
        </div>
        <!-- 下方整行显示的子分类树 -->
        <div class="category-tree-panel" v-if="activeTopCategoryId && expandedCategories[activeTopCategoryId]">
          <CategoryTree
              :parentId="activeTopCategoryId"
              :subCategories="subCategories"
              :expandedCategories="expandedCategories"
              :fetch="fetchSubCategories"
              :depth="1"
              @item-click="selectOrExpand"
          />
        </div>
      </div>
    </div>
    <!-- 分类标签END -->

    <!-- 主要内容区 -->
    <div class="main">
      <div class="list">
        <MyList :list="product" v-if="product.length>0"></MyList>
        <div v-else class="none-product">抱歉没有找到相关的商品，请看看其他的商品</div>
      </div>
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            background
            layout="prev, pager, next"
            :page-size="pageSize"
            :total="total"
            @current-change="currentChange"
        ></el-pagination>
      </div>
      <!-- 分页END -->
    </div>
    <!-- 主要内容区END -->
  </div>
</template>
<script>
export default {
  components: {
    CategoryTree: {
      name: 'CategoryTree',
      props: {
        parentId: { type: Number, required: true },
        subCategories: { type: Object, required: true },
        expandedCategories: { type: Object, required: true },
        fetch: { type: Function, required: false },
        depth: { type: Number, default: 1 }
      },
      created() {
        if (this.fetch && !this.subCategories[this.parentId]) {
          this.fetch(this.parentId).catch(() => {});
        }
      },
      methods: {
        onClick(item) {
          this.$emit('item-click', item);
        }
      },
      render(h) {
        const children = this.subCategories[this.parentId] || [];
        if (!children.length) return null;
        const wrapperClass = ['tree-level', `depth-${this.depth}`];
        return h('div', { class: wrapperClass }, children.map(subItem => {
          const isExpanded = !!this.expandedCategories[subItem.id];
          const icon = h('i', {
            class: {
              'el-icon-arrow-right': true,
              'expand-icon': true,
              'expanded': isExpanded
            }
          });
          const row = h('div', {
            key: subItem.id,
            class: 'tree-item',
            on: { click: (e) => { e.stopPropagation(); this.onClick(subItem); } }
          }, [
            h('span', { class: 'category-name' }, subItem.name),
            icon
          ]);
          const nested = isExpanded ? h('CategoryTree', {
            props: {
              parentId: subItem.id,
              subCategories: this.subCategories,
              expandedCategories: this.expandedCategories,
              fetch: this.fetch,
              depth: this.depth + 1
            },
            on: { 'item-click': (it) => this.onClick(it) }
          }) : null;
          return h('div', { class: 'tree-wrapper' }, [row, nested]);
        }));
      }
    }
  },
  data() {
    return {
      categoryList: "", //分类列表
      categoryID: [], // 分类id
      product: "", // 商品列表
      productList: "",
      total: 0, // 商品总量
      pageSize: 15, // 每页显示的商品数量
      currentPage: 1, //当前页码
      activeName: "-1", // 分类列表当前选中的id
      search: "", // 搜索条件
      subCategories: {}, // 存储每个分类的子分类
      expandedCategories: {}, // 存储哪些分类是展开状态
      activeTopCategoryId: null // 当前选中的一级分类，用于在面板中展示
    };
  },
  created() {
    // 获取分类列表
    this.getCategory();
  },
  activated() {
    this.activeName = "-1"; // 初始化分类列表当前选中的id为-1
    this.total = 0; // 初始化商品总量为0
    this.currentPage = 1; //初始化当前页码为1
    // 如果路由没有传递参数，默认为显示全部商品
    if (Object.keys(this.$route.query).length == 0) {
      this.categoryID = [];
      this.activeName = "0";
      return;
    }
    // 如果路由传递了categoryID，则显示对应的分类商品
    if (this.$route.query.categoryID != undefined) {
      this.categoryID = this.$route.query.categoryID;
      if (this.categoryID.length == 1) {
        this.activeName = "" + this.categoryID[0];
      }
      return;
    }
    // 如果路由传递了search，则为搜索，显示对应的分类商品
    if (this.$route.query.search != undefined) {
      this.search = this.$route.query.search;
    }
  },
  watch: {
    // 监听点击了哪个分类标签，通过修改分类id，响应相应的商品
    activeName: function(val) {
      if (val == 0) {
        this.categoryID = [];
      }
      if (val > 0) {
        this.categoryID = [Number(val)];
      }
      // 初始化商品总量和当前页码
      this.total = 0;
      this.currentPage = 1;
      // 更新地址栏链接，方便刷新页面可以回到原来的页面
      this.$router.push({
        path: "/goods",
        query: { categoryID: this.categoryID }
      });
    },
    // 监听搜索条件，响应相应的商品
    search: function(val) {
      if (val != "") {
        this.getProductBySearch(val);
      }
    },
    // 监听分类id，响应相应的商品
    categoryID: function() {
      this.getData();
      this.search = "";
    },
    // 监听路由变化，更新路由传递了搜索条件
    $route: function(val) {
      if (val.path == "/goods") {
        if (val.query.search != undefined) {
          this.activeName = "-1";
          this.currentPage = 1;
          this.total = 0;
          this.search = val.query.search;
        }
      }
    }
  },
  methods: {
    // 返回顶部
    backtop() {
      const timer = setInterval(function() {
        const top = document.documentElement.scrollTop || document.body.scrollTop;
        const speed = Math.floor(-top / 5);
        document.documentElement.scrollTop = document.body.scrollTop =
            top + speed;

        if (top === 0) {
          clearInterval(timer);
        }
      }, 20);
    },
    // 页码变化调用currentChange方法
    currentChange(currentPage) {
      this.currentPage = currentPage;
      console.log(this.search + "1234566")
      this.getProductBySearch();
      this.backtop();
    },
    // 向后端请求分类列表数据
    getCategory() {
      this.$axios
          .get("/api/v1/category/getChildren", {
            params: {
              parentId: 1
            }
          })
          .then(res => {
            const val = {
              category_id: 0,
              category_name: "全部"
            };
            const cate = res.data.data;
            cate.unshift(val);
            this.categoryList = cate;
          })
          .catch(err => {
            return Promise.reject(err);
          });
    },
    // 向后端请求全部商品或分类商品数据
    getData() {
      // 如果分类列表为空则请求全部商品数据，否则请求分类商品数据
      const api =
          this.categoryID.length === 0
              ? "/api/v1/good/getAll"
              : "/api/v1/good/getByCategoryId";

      // 构建请求参数
      const params = {
        currentPage: this.currentPage,
        pageSize: this.pageSize
      };

      // 如果有分类ID，添加categoryId参数
      if (this.categoryID.length > 0) {
        params.categoryId = this.categoryID[0]; // 取第一个分类ID
      }

      this.$axios
          .get(api, { params })
          .then(res => {
            this.product = res.data.data;
            this.total = res.data.data.length;
          })
          .catch(err => {
            return Promise.reject(err);
          });
    },
    // 通过搜索条件向后端请求商品数据
    getProductBySearch() {
      this.$axios
          .get("/api/v1/good/getGoodBySearch", {
            params: {
              name: this.search,
              page: this.currentPage,
              size: this.pageSize
            }
          })
          .then(res => {
            this.product = res.data.data;
            this.total = res.data.total;
          })
          .catch(err => {
            return Promise.reject(err);
          });
    },
    // 获取指定分类的子分类
    async fetchSubCategories(parentId) {
      if (this.subCategories[parentId]) {
        return this.subCategories[parentId];
      }
      try {
        const res = await this.$axios.get("/api/v1/category/getChildren", {
          params: { parentId }
        });
        const list = res.data && res.data.data ? res.data.data : [];
        if (!Array.isArray(list) || list.length === 0) {
          this.$set(this.subCategories, parentId, []);
          return [];
        }
        this.$set(this.subCategories, parentId, list);
        return list;
      } catch (err) {
        this.$set(this.subCategories, parentId, []);
        return [];
      }
    },
    // 检查分类是否有子分类
    hasSubCategories(categoryId) {
      return this.subCategories[categoryId] && this.subCategories[categoryId].length > 0;
    },
    // 处理分类点击事件
    isTopLevel(id) {
      if (!Array.isArray(this.categoryList)) return false;
      return this.categoryList.findIndex(c => c.id === id) !== -1;
    },
    async selectOrExpand(item) {
      // 如果点击的是"全部"分类
      console.log(item)
      if (item.category_id === 0) {
        this.activeName = "0";
        this.categoryID = [];
        this.search = "";
        this.total = 0;
        this.currentPage = 1;
        this.expandedCategories = {};
        console.log("-------------------------全部")
        return;
      }

      // 点击了一级分类时，先关闭其它下拉
      if (this.isTopLevel(item.id)) {
        this.expandedCategories = {};
        this.activeTopCategoryId = item.id;
      }

      const children = await this.fetchSubCategories(item.id);
      if (children && children.length > 0) {
        // 对当前行进行展开/收起
        this.$set(this.expandedCategories, item.id, !this.expandedCategories[item.id]);
      } else {
        this.activeName = "" + item.id;
        this.categoryID = [item.id];
        this.search = "";
        this.total = 0;
        this.currentPage = 1;
        // 选择叶子节点后，不用收起其它分支
      }
    },
    toggleExpand(id) {
      // 先尝试预取，随后切换
      this.fetchSubCategories(id).finally(() => {
        this.$set(this.expandedCategories, id, !this.expandedCategories[id]);
      });
    }
  }
};
</script>

<style scoped>
.goods {
  background-color: #f5f5f5;
}
/* 面包屑CSS */
.el-tabs--card .el-tabs__header {
  border-bottom: none;
}
.goods .breadcrumb {
  height: 50px;
  background-color: white;
}
.goods .breadcrumb .el-breadcrumb {
  width: 1225px;
  line-height: 30px;
  font-size: 16px;
  margin: 0 auto;
}
/* 面包屑CSS END */

/* 分类标签CSS */
.goods .nav {
  background-color: white;
  position: relative;
  z-index: 10;
}
.goods .nav .product-nav {
  width: 1225px;
  min-height: 40px;
  margin: 0 auto;
  padding: 8px 0;
  overflow: visible;
}
.nav .product-nav .title {
  width: 50px;
  font-size: 16px;
  font-weight: 700;
  float: left;
  line-height: 40px;
}
.category-tabs {
  display: flex;
  flex-wrap: wrap;
  margin-left: 60px;
  align-items: flex-start;
}
.category-tree-panel {
  width: 100%;
  margin-left: 60px;
  margin-top: 8px;
  padding: 10px 12px;
  background: #fff;
  border: 1px solid #eaeaea;
  border-radius: 6px;
}
.category-item {
  position: relative;
  padding: 0 15px;
  margin-right: 10px;
  cursor: pointer;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: #f5f5f5;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  height: 32px;
  margin-top: 4px;
}
.category-item:hover {
  background-color: #e6f7ff;
  border-color: #1890ff;
}
.category-item.active {
  background-color: #1890ff;
  color: white;
  border-color: #1890ff;
}
.category-name {
  font-size: 14px;
}
.expand-icon {
  margin-left: 5px;
  font-size: 12px;
  transition: transform 0.3s;
}
.expand-icon.expanded {
  transform: rotate(180deg);
}
/* 垂直树样式 */
::v-deep .tree-level {
  margin-left: 16px;
  padding-left: 10px;
  border-left: 2px dashed #e6e6e6;
}
::v-deep .tree-level.depth-1 { background: #ffffff; }
::v-deep .tree-level.depth-2 { background: #f7fbff; }
::v-deep .tree-level.depth-3 { background: #f6fff9; }
::v-deep .tree-level.depth-4 { background: #fff8f0; }
::v-deep .tree-item {
  padding: 6px 8px;
  cursor: pointer;
  font-size: 14px;
  line-height: 20px;
  border-radius: 4px;
  margin: 2px 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
::v-deep .tree-item:hover { background: #eef6ff; }
/* 分类标签CSS END */

/* 主要内容区CSS */
.goods .main {
  margin: 0 auto;
  max-width: 1225px;
}
.goods .main .list {
  min-height: 650px;
  padding-top: 14.5px;
  margin-left: -13.7px;
  overflow: auto;
}
.goods .main .pagination {
  height: 50px;
  text-align: center;
}
.goods .main .none-product {
  color: #333;
  margin-left: 13.7px;
}
/* 主要内容区CSS END */
</style>